// package com.ambitious.controller;
//
// import com.alibaba.fastjson.JSONObject;
// import com.ambitious.domain.Grade;
// import com.ambitious.domain.token.IndexToken;
// import com.ambitious.domain.Student;
// import org.apache.http.NameValuePair;
// import org.apache.http.client.entity.UrlEncodedFormEntity;
// import org.apache.http.client.methods.CloseableHttpResponse;
// import org.apache.http.client.methods.HttpGet;
// import org.apache.http.client.methods.HttpPost;
// import org.apache.http.cookie.Cookie;
// import org.apache.http.impl.client.BasicCookieStore;
// import org.apache.http.impl.client.CloseableHttpClient;
// import org.apache.http.impl.client.HttpClientBuilder;
// import org.apache.http.impl.client.HttpClients;
// import org.apache.http.message.BasicNameValuePair;
// import org.apache.http.util.EntityUtils;
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.web.bind.annotation.*;
//
// import javax.servlet.ServletOutputStream;
// import javax.servlet.http.HttpServletRequest;
// import javax.servlet.http.HttpServletResponse;
// import javax.servlet.http.HttpSession;
// import java.io.IOException;
// import java.util.ArrayList;
// import java.util.List;
// import java.util.Map;
//
// /**
//  * @author Ambitious
//  */
// @RestController
// @CrossOrigin
// public class GradeController {
//
//     @Autowired
//     private BasicCookieStore cookieStore;
//     @Autowired
//     private Map<Integer,CloseableHttpClient> clientMap;
//     private Integer clientNum = 0;
//
//     private Logger logger = LoggerFactory.getLogger(GradeController.class);
//
//     @PostMapping("/get-grade")
//     public List<Grade> getGrade(@RequestBody Student student) throws IOException {
//         CloseableHttpClient httpClient = clientMap.get(student.getClientId());
//         // 代理发送http请求拿到数据
//         HttpPost post = new HttpPost("https://cas.gzhu.edu.cn/cas_server/login");
//         // 设置表单请求参数
//         List<NameValuePair> urlParams = new ArrayList<>();
//         urlParams.add(new BasicNameValuePair("username",student.getStuNum()));
//         urlParams.add(new BasicNameValuePair("password",student.getPassword()));
//         urlParams.add(new BasicNameValuePair("captcha",student.getCaptcha()));
//         urlParams.add(new BasicNameValuePair("lt",student.getLt()));
//         urlParams.add(new BasicNameValuePair("execution",student.getExecution()));
//         urlParams.add(new BasicNameValuePair("_eventId","submit"));
//         urlParams.add(new BasicNameValuePair("warn","true"));
//         post.setEntity(new UrlEncodedFormEntity(urlParams));
//         post.setHeader("Cookie","JSESSIONID="+student.getJSessionId());
//         // 发送请求
//         // 2 使用客户端对象发送请求
//         cookieStore.clear();
//         httpClient.execute(post);
//         List<Cookie> cookies = cookieStore.getCookies();
//         // 拿到进入教务系统的token
//         String accessToken = "";
//         for (Cookie cookie : cookies) {
//             if("CASTGC".equals(cookie.getName())){
//                 accessToken = cookie.getValue();
//             }
//         }
//         logger.info("accessToken:{}",accessToken);
//         // 3 新建一个进入教务系统的请求
//         HttpGet get = new HttpGet("https://cas.gzhu.edu.cn/cas_server/login?service=http%3A%2F%2Fjwxt.gzhu.edu.cn%2Fsso%2Flyiotlogin");
//         get.addHeader("Cookie","CASTGC="+accessToken);
//         cookieStore.clear();
//         // 发送get请求
//         httpClient.execute(get);
//         List<Cookie> cookieList = cookieStore.getCookies();
//         String newSessionId = "";
//         String cookie18 = "";
//         for (Cookie cookie : cookieList) {
//             if("JSESSIONID".equals(cookie.getName())){
//                 newSessionId = cookie.getValue();
//             }else if("SF_cookie_18".equals(cookie.getName())){
//                 cookie18 = cookie.getValue();
//             }
//         }
//         // 4 根据拿到的两个值查询成绩
//         post = new HttpPost("http://jwxt.gzhu.edu.cn/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&su="+student.getStuNum());
//         // 设置请求体参数
//         urlParams = new ArrayList<>();
//         urlParams.add(new BasicNameValuePair("xnm",student.getYear()));
//         urlParams.add(new BasicNameValuePair("xqm",student.getTerm()));
//         urlParams.add(new BasicNameValuePair("queryModel.showCount","100"));
//         post.setEntity(new UrlEncodedFormEntity(urlParams));
//         // 设置请求头参数
//         post.setHeader("Cookie","JSESSIONID="+newSessionId+"; SF_cookie_18="+cookie18);
//         // 发送请求
//         CloseableHttpResponse response3 = httpClient.execute(post);
//         String value = EntityUtils.toString(response3.getEntity());
//         // 将返回的结果封装为对象
//         // 1 拿到items数组对应的字符串
//         JSONObject jsonObject = JSONObject.parseObject(value);
//         String grades = jsonObject.getString("items");
//         // 2 去除字符串头尾两个中括号
//         grades = grades.substring(1, grades.length() - 1);
//         // 3 将字符串拆分
//         String[] gradeListStr = grades.split("},\\{");
//         List<Grade> gradeList = new ArrayList<>();
//         for (String s : gradeListStr) {
//             // 将大括号补充完整
//             StringBuffer tmp = new StringBuffer();
//             if(!s.startsWith("{")){
//                 tmp.append('{');
//             }
//             tmp.append(s);
//             if(!s.endsWith("}")){
//                 tmp.append('}');
//             }
//             Grade grade = JSONObject.parseObject(tmp.toString(), Grade.class);
//             gradeList.add(grade);
//         }
//         httpClient.close();
//         // 将Map中当前的客户端号移除
//         clientMap.remove(student.getClientId());
//         return gradeList;
//     }
//
//     @GetMapping(value = "/get-captcha",produces = "image/jpeg;charset=utf-8")
//     public void getCaptcha(HttpServletResponse httpResponse,String jSessionId,int clientId) throws IOException {
//         // 根据clientId拿到httpClient对象
//         CloseableHttpClient httpClient = clientMap.get(clientId);
//         // 新建一个get请求
//         HttpGet get = new HttpGet("https://cas.gzhu.edu.cn/cas_server/captcha.jsp");
//         // 设置cookie
//         get.addHeader("Cookie","JSESSIONID="+jSessionId);
//         // 使用客户端发送请求，拿到验证码
//         CloseableHttpResponse response = httpClient.execute(get);
//         // 将请求到的数据直接写入到输出流中
//         ServletOutputStream outputStream = httpResponse.getOutputStream();
//         response.getEntity().writeTo(outputStream);
//         outputStream.println();
//     }
//
//     @GetMapping("/get-index")
//     public IndexToken getIndex() throws IOException {
//         // 发送get请求给数字广大登录页面
//         // 每次刷新页面都需要重新创建一个httpClient
//         CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//         IndexToken indexToken = new IndexToken();
//         HttpGet get = new HttpGet("https://cas.gzhu.edu.cn/cas_server/login");
//         cookieStore.clear();
//         CloseableHttpResponse response = httpClient.execute(get);
//         List<Cookie> cookies = cookieStore.getCookies();
//         for (Cookie cookie : cookies) {
//             if("JSESSIONID".equals(cookie.getName())){
//                 indexToken.setJSessionId(cookie.getValue());
//             }
//         }
//         String value = EntityUtils.toString(response.getEntity());
//         // 拿到校验码lt
//         int ltIndex = value.indexOf("value=\"LT");
//         String lt = value.substring(ltIndex).split("\"")[1];
//         indexToken.setLt(lt);
//         // 拿到校验码execution
//         int exeIndex = value.indexOf("execution");
//         String execution = value.substring(exeIndex+18,exeIndex+22);
//         indexToken.setExecution(execution);
//         // 需要使用当前客户端继续操作不能关闭，需要将其存储到map中
//         int clientId = ++clientNum;
//         clientMap.put(clientId,httpClient);
//         indexToken.setClientId(clientId);
//         return indexToken;
//     }
//
// }
